package com.sicau.imagesearchmcpserver.tools;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class ImageSearchTool {

    private String pexelsApiKey;

    private static final String PEXELS_SEARCH_URL = "https://api.pexels.com/v1/search";

    @Tool(description = "图片搜索工具, 返回图片的url列表")
    public String ImageSearch(
            @ToolParam(description = "待搜索的图片的关键字") String keyword){

        // 处理默认参数值
        int actualPerPage = 10;
        int actualPage = 1;
        String requestUrl = null;

        try {
            // 构建请求URL，使用Hutool的URL编码工具处理关键词中的特殊字符
            String encodedKeyword = URLEncoder.encode(keyword, "UTF-8");
            requestUrl = String.format("%s?query=%s&per_page=%d&page=%d",
                    PEXELS_SEARCH_URL,
                    encodedKeyword,
                    actualPerPage,
                    actualPage);
        } catch (UnsupportedEncodingException e) {
            return "Image search failed! Invalid keyword.";
        }

        Map<String, String> envs = System.getenv();
        pexelsApiKey = envs.getOrDefault("PEXELS_API_KEY", "0");

        try (HttpResponse response = HttpRequest.get(requestUrl)
                // 设置Authorization请求头
                .header("Authorization", pexelsApiKey)
                // 设置超时时间（超时10秒）
                .timeout(10000)
                // 发送请求并获取响应
                .execute()) {

            // 检查响应状态码，200表示成功
            if (response.isOk()) {
                // 直接返回JSON格式的响应结果
                String body = response.body();
                JSONArray photos = JSONUtil.parseObj(body).getJSONArray("photos");
                if (photos != null && !photos.isEmpty()) {
                    StringBuilder result = new StringBuilder("Image Search Results:\n");
                    photos.forEach(photo -> {
                        JSONObject photoObj = (JSONObject) photo;
                        result.append("Image Url: ").append(photoObj.getStr("url")).append("\n");
                    });
                    return result.toString();
                } else {
                    return "No images found for the given keyword.";
                }
            } else {
                // 处理请求失败的情况，返回错误信息
                return String.format("Image search failed! Status code: %d, Error message: %s",
                        response.getStatus(),
                        response.body());
            }

        } catch (Exception e) {
            // 捕获异常并返回友好提示
            return String.format("Image search encountered an error: %s", e.getMessage());
        }
    }
}